<template>
  <div class="form">
    <el-form ref="formRef" :model="form" :rules="rules" label-position="right" label-width="70px">
      <el-form-item prop="username" label="用户名">
        <el-input v-model="form.username" class="shortInput"/>
      </el-form-item>
      <el-form-item prop="password" label="密码">
        <el-input type="password" v-model="form.password" class="shortInput" />
      </el-form-item>
      <el-button size="large" class="subBtn" @click="doLogin">点击登录</el-button>
    </el-form>
  </div>
</template>

<script setup lang="js">
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import { useUserStore } from '@/stores/user';
import router from '@/router';
import JSEncrypt from 'jsencrypt';

//公钥
const publicKey ='MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCW0GPS4xex6X3hb34aHREHS4TpWlr1bdYea7Db6k5U6gH06YekUGgsvrtBu7xtVz6nEThfp2RoPkTUoEdAQNRC6RMU9hjRq/96Zfcy+LM884Ip9W/YNBHHG3/tT7Hv8sDr3XCvD3R5KNHR1VjuzXqpaHfUVxZJREMZB30HKBhSPQIDAQAB';

//加密密码的函数
//使用公钥对密码进行加密
const encryptPassword = (password) => {
  const crypt = new JSEncrypt();
  crypt.setPublicKey(publicKey);
  return crypt.encrypt(password);
}

const userStore = useUserStore();

const form = ref({
  username: '',
  password: '',
});

const rules = {
  username: [
    { required: true, message: '用户名不能为空', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    { min: 6, max: 14, message: '密码长度要求6-14个字符', trigger: 'blur' }
  ]
};

const formRef = ref(null);

const doLogin = async () => {
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
         //加密密码
        const cryptPassword = encryptPassword(form.value.password);

        //将用户名和加密的密码发送到后端进行验证
        await userStore.getUserInfo({ username: form.value.username,  password: cryptPassword});
        if (userStore.userInfo) {
          ElMessage({ type: 'success', message: '登录成功' });
          router.replace({ path: '/home' });
        } else {
          ElMessage({ type: 'error', message: '用户名或密码错误' });
        }
      } catch (error) {
        console.error('登录失败:', error);
        ElMessage({ type: 'error', message: '登录失败，请重试' });
      }
    }
  });
};
</script>

<style scoped>
.shortInput {
  width: 200px;
}
</style>